package com.yunshang.ysmall.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ognl.MemberAccess;

import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingplusplus.Pingpp;
import com.pingplusplus.exception.APIConnectionException;
import com.pingplusplus.exception.APIException;
import com.pingplusplus.exception.AuthenticationException;
import com.pingplusplus.exception.ChannelException;
import com.pingplusplus.exception.InvalidRequestException;
import com.pingplusplus.exception.RateLimitException;
import com.pingplusplus.model.Charge;
import com.pingplusplus.util.WxpubOAuth;
import com.yunshang.ysmall.mapper.MemberInfoMapper;
import com.yunshang.ysmall.model.MbAddrInfo;
import com.yunshang.ysmall.model.MemberInfo;
import com.yunshang.ysmall.model.OrderInfo;
import com.yunshang.ysmall.model.OrderItemInfo;
import com.yunshang.ysmall.model.ProductInfo;
import com.yunshang.ysmall.model.ReturnFanchang;
import com.yunshang.ysmall.model.TrackingInFormation;
import com.yunshang.ysmall.service.MemberService;
import com.yunshang.ysmall.util.Constants;
import com.yunshang.ysmall.util.DateUtils;
import com.yunshang.ysmall.util.HttpClientUtils;
import com.yunshang.ysmall.util.KdApiOrderDistinguish;
import com.yunshang.ysmall.util.KdniaoTrackQueryAPI;
import com.yunshang.ysmall.util.MD5Utils;

@Controller
@RequestMapping("/member")
public class MemberController {
	private static Logger logger = LoggerFactory.getLogger(OrderController.class);
	@Resource
	MemberService memberService;
	
	public static final String ROOT = "src/main/resources/static/upload-dir";
	
	public static final String url = "http://www.yssy7.com/scapi.aspx?client_id=YUNSHANG08";
	public static final String key = "ys123456";
	
	
	
	
	@ResponseBody
	@RequestMapping("/login")
	public String login(MemberInfo memberInfo,HttpServletRequest request,Model model){
		String schemaName =  "GET_USER_LOGIN";
		try {
			//对用户名和密码进行编码
			String param = URLEncoder.encode("{\"USER_ALIAS\":\""+memberInfo.getMemberId()+"\",\"PASSWORD1\":\""+MD5Utils.MD5(memberInfo.getPassword()).toLowerCase()+"\"}","utf-8");
			String ndate = DateUtils.currentDate("HHmmss");
			//当前时间和密码进行加密
			String md5 = MD5Utils.MD5("YUNSHANG08"+key+ndate).toLowerCase();
			String requestUrl = url+"&schema_name="+schemaName+"&parameter="+param+"&ndate="+ndate+"&md5="+md5;
			String result = HttpClientUtils.httpGet(requestUrl);
//			System.out.println("result:"+result);
			//{"result":"success","total":1,"data":[{"NAME":"乔江2","DWALLET":"0.74","USER_ALIAS":"AN809702","PASSWORD":"96e79218965eb72c92a549dd5a330112","ISLOGIN":1.0}]};
//				测试的json数据
			//String result="{'result':'success','total':1,'data':[{'NAME':'乔江2','DWALLET':'0.74','USER_ALIAS':'AN809702','PASSWORD':'96e79218965eb72c92a549dd5a330112','ISLOGIN':1.0}]}";
			JSONObject jsonObject = JSONObject.parseObject(result);
			if("success".equals(jsonObject.getString("result"))){
				JSONObject data = jsonObject.getJSONArray("data").getJSONObject(0);
				if(!"".equals(data.getString("NAME"))){
					memberInfo.setNickName(data.getString("NAME"));
				}else{
					return "{\"result\":\"fail\"}";
				}
				if(!"".equals(data.getString("DWALLET"))){
					memberInfo.setBonusBalance(data.getBigDecimal("DWALLET"));
				}
				memberService.loginHandle(memberInfo);
//				model.addAttribute("memberInfo", memberInfo);
				//登录成功将会员的信息存入到"memberInfo"中
				request.getSession().setAttribute(Constants.LOGIN_MEMBER, memberInfo);
				//并且讲会员的id存入到中"memberId"
				request.getSession().setAttribute(Constants.MEMBER_ID, memberInfo.getMemberId());
				
				return "{\"result\":\"success\"}";
			}
			return "{\"result\":\"fail\"}";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "{\"result\":\"fail\"}";
		}
	}
	
	@RequestMapping("/wechat")
	public String wechat(String code,HttpServletRequest request, Model model) throws Exception{
		logger.info("###########################");
		logger.info("code:"+code);
		if(code == null){
			return null;
		}
		try {
			String openId = WxpubOAuth.getOpenId("wx0c79bdb59eb72939", "a511700e96b37ca88f10c762e176991c", code);
//			String openId ="o0qua0_mj3wJD6YwipdgyBTpWZ9U";
			logger.info("openId:"+openId);
			logger.info("###########################");
			OrderInfo orderInfo = (OrderInfo)request.getSession().getAttribute("orderInfo");
			orderInfo.setOpenId(openId);
			model.addAttribute("orderInfo", orderInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "/mall/prepay2";
	}
	
	
	@RequestMapping("/main")
	public String main(HttpServletRequest request,Model model){
		//	从session中判断"memberInfo"的值是否为空
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		//当session值不为空的时候跳到会员页面
		return "/mall/mbmain";
	}
	
	//退出登录
	@RequestMapping("/userLoginQuit")
	public String quitLogin(HttpServletRequest request,HttpServletResponse response) throws IOException{
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER)!=null){
			//清空会员信息和会员id号
			request.getSession().removeAttribute(Constants.LOGIN_MEMBER);
			request.getSession().removeAttribute(Constants.MEMBER_ID);
		}
		return  "mall/login";
	}
	
	//获取代支付展示页面
	@RequestMapping("/prepay/{step}")
	public String prepay(@PathVariable("step") Integer step,HttpServletRequest request,Model model){
		//判断会员是否登录
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		request.getSession().setAttribute("step", String.valueOf(step));
		request.getSession().setAttribute("itemCount", request.getParameter("itemCount"));
		
		//获取会员的id号去查询会员的信息
		MbAddrInfo mbAddrInfo = memberService.getAddrByMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
		model.addAttribute("mbAddrInfo", mbAddrInfo);
		//创建一个订单详细列表的集合对象
		List<OrderItemInfo> itemList = new ArrayList<OrderItemInfo>();
		//创建一个订单信息对象
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
		
		//直接购买进入
		if(1== step){
//			订单的详细列表
			OrderItemInfo itemInfo = new OrderItemInfo();
			System.out.println("###############");
			System.out.println(request.getParameter("productId"));
			System.out.println(request.getParameter("productName"));
			System.out.println(request.getParameter("count"));
			System.out.println(request.getParameter("price"));
			System.out.println(request.getParameter("bonus"));
			System.out.println("###############");
			itemInfo.setProductId(request.getParameter("productId"));
			itemInfo.setProName(request.getParameter("productName"));
			itemInfo.setSmallImgPath(request.getParameter("smallImgPath"));
			itemInfo.setCount(Integer.parseInt(request.getParameter("count")));
			//将直接购买的数量和产品id存入的session中
			request.getSession().setAttribute("outrightPurchase", itemInfo.getCount());
			request.getSession().setAttribute("outrightProductId", itemInfo.getProductId());
			itemInfo.setTransAmt(new BigDecimal(request.getParameter("price")));
			itemInfo.setTransBonus(new BigDecimal(request.getParameter("bonus")));
			//计算消费总金额.
			orderInfo.setTransAmt(itemInfo.getTransAmt().multiply(new BigDecimal(itemInfo.getCount())));
			//计算消费总积分
			orderInfo.setTransBonus(itemInfo.getTransBonus().multiply(new BigDecimal(itemInfo.getCount())));
			itemList.add(itemInfo);
		}
		//购物车结算进入下订单页面
		if(2== step){
			//获取购物车的信息
			Map<String,OrderItemInfo> cartMap = (Map<String,OrderItemInfo>) request.getSession().getAttribute(Constants.MEMBER_CART);
			//查看购物车中选中的商品
			Map<String,OrderItemInfo> checkedMap = (Map<String,OrderItemInfo>) request.getSession().getAttribute(Constants.CHECKED_CART);
			//如果页面传过来商品的种类和购物车选择的种类不一致则返回到购物车页面
			if(Integer.parseInt(request.getParameter("itemCount")) != checkedMap.size()){
				return "/mall/cart";
			}
			//讲消费总金额和消费的总积分置为0
			BigDecimal transAmt = BigDecimal.ZERO;
			BigDecimal transBonus = BigDecimal.ZERO;
			//获取集合中所有的商品id
			for (String productId : checkedMap.keySet()) {
				//通过指定的商品id获订单详细信息。
				OrderItemInfo checkdItem = checkedMap.get(productId);
				//订单详细添加到集合中
				itemList.add(checkdItem);
				//这里只是获取每个订单详细表中购买的数量。并且求出总的消费金额和总的消费积分
				transAmt = transAmt.add(checkdItem.getTransAmt().multiply(new BigDecimal(checkdItem.getCount())));
				//将每个
				transBonus = transBonus.add(checkdItem.getTransBonus().multiply(new BigDecimal(checkdItem.getCount())));
			//清除购物车中的商品
				cartMap.remove(productId);
			}
			//清除购物车的信息
			checkedMap.clear();
			orderInfo.setTransAmt(transAmt);
			orderInfo.setTransBonus(transBonus);
			//将清空后的购物车重新放入到session中
			request.getSession().setAttribute(Constants.MEMBER_CART, cartMap);
			
			
			
			
		}
		model.addAttribute("itemList", itemList);
		//将订单详细信息存入都session中。封装了总的金额，总的积分，会员编号
		request.getSession().setAttribute("sureList", itemList);
		model.addAttribute("orderInfo", orderInfo);
		return "/mall/prepay";
	}
	
	
	//支付生成订单
	@ResponseBody
	@RequestMapping("/dopay")
	public String dopay(OrderInfo orderInfo,HttpServletRequest request,Model model){
		//判断会员是否登录
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		//从session中获取会员信息
		MemberInfo memberInfo = (MemberInfo)request.getSession().getAttribute(Constants.LOGIN_MEMBER);
		//判断当前的订单总积分多如果比会员剩余的总积分大，则说明会员积分不足
		if(orderInfo.getTransBonus().compareTo(memberInfo.getBonusBalance()) > 0){
			return "{\"result\":\"fail\",\"msg\":\"会员积分不足\"}";
		}
		
//		if("wx".equals(orderInfo.getPayChannel()) && orderInfo.getOpenId() == null){
//			request.getSession().setAttribute("orderInfo", orderInfo);
//			return "{\"result\":\"success2\",\"msg\":\"http://localhost:8080/member/wechat?code=1234\"}";
//		}
		
		//获取返回请求头的值是否包含此字符串，User-Agent   作用：告诉HTTP服务器， 客户端使用的操作系统和浏览器的名称和版本.
		/*String ua = request.getHeader("user-agent").toLowerCase();
		//将其输入到日志当中
		logger.info("ua:"+ua);*/
		//判断该字符串是否出现
			//判断传递过来的是否是微信支付。并且
			/*if("ali".equals(orderInfo.getPayChannel()) ){
				return "{\"result\":\"fail\",\"msg\":\"请在右上角用浏览器打开\"}";
			}*/
		
		//获取随机数
		int ran = (int)(Math.random()*9000) + 1000;
		//通过指定格式来设置订单的编号,时间
		orderInfo.setOrderId("HH"+DateUtils.currentDate("MMddHHmmss")+ran);
		orderInfo.setOrderDate(DateUtils.currentDate("yyyyMMdd"));
		orderInfo.setOrderTime(DateUtils.currentDate("HHmmss"));
		//设置订单的状态为待支付的状态
		orderInfo.setOrderStatus(0);
		//保存订单
		if(memberService.saveOrder(orderInfo)){
			//从session中获取订单详细列表
			List<OrderItemInfo> itemList = (List<OrderItemInfo>)request.getSession().getAttribute("sureList");
			for (OrderItemInfo orderItemInfo : itemList) {
				//将订单信息的编号存入到订单详细中
				orderItemInfo.setOrderId(orderInfo.getOrderId());
				//保存订单详细列表
				memberService.saveOrderItem(orderItemInfo);
			}
		}
		//ping++ 的密钥
		Pingpp.apiKey = "sk_live_az9uXH484iX9eDKGW5rjfPmL";
		Pingpp.privateKey = "-----BEGIN PRIVATE KEY-----\n" +
                "MIICXAIBAAKBgQChXY7SytFezkMSpyaWbh90ZWNdjERZVuSb6OcqRIILXA7o4LsP\n" + 
                "ZCIZly2vlJ5xjSAe/DiEGI1siHRuHdYghDWyzg+CfAQLJiwXI+7+4ffdZss9hKkZ\n" + 
                "EBYjYjt7OgtRUxrAob/YWF//HBaxCkhgAWoerbf/oORm+fNAHGNwYOUQ2wIDAQAB\n" + 
                "AoGAMUnUgEp3HVA/aIkp3jUQ4oq9iSt5DRjfh0fipCR83F9oJnXObWsWh16IE+N/\n" + 
                "agvDTfOYh7DAMfCUL7ZpW1FG3TSfAvnhrT5q+v8s0dYnhU7ANZ9iKpHXK2y+wu/3\n" + 
                "2u6KbjZqopsXrMhQzaV4zQkMljonU1MnxL6Bjqo+xmYamWECQQDRiJ0jG5qToHjs\n" + 
                "DOasY8vi7aCtv1JDLGWIw5eCQghM98yYiuA/kLB34OGYzdDlTg65rgECGmOttOQ3\n" + 
                "jgEpzFJTAkEAxSZmKsjJX9/gSBnxFvIFASXc47RSPv1eWJvueftuIZAu05y/WFbk\n" + 
                "cilNvSfChX3aNOHlheoP5103JGzeFIeGWQJBAIxF6vyv5CHkkk9kq6DJBpua/bCT\n" + 
                "npy9whN27Z0UW747Pkr43ftv/9OhRyYm0yxPv2fq513jEMwfh5DxjjHPSWUCQDQy\n" + 
                "GWSEakQ22oNcUucXRlnqc1PZ3tiMbhkZl4a2GY9LRAqEemhiAPN0mf9VcnuzOT08\n" + 
                "/W557KH9nObI5/cZdmkCQAuo/TirHFdBo0lLsIBAT5SvK5Gwd2x4Ru0NOvyZNnb1\n" + 
                "fEnjp0itbyoeT0Jk6Cmmml9rh3pDcXgIArbdYSpM8Yg=\n" +                     
                "-----END PRIVATE KEY-----\n";
		//创建ping++的对象
		Charge charge = null;
		//将订单的编号存入到集合中
		Map<String, Object> chargeParams = new HashMap<String, Object>();
		//商户的订单号
		chargeParams.put("order_no", orderInfo.getOrderId());
		//订单的总金额  ，将总金额的小数点向右移动两位。
		chargeParams.put("amount", orderInfo.getTransAmt().movePointRight(2).toString());// 订单总金额, 人民币单位：分（如订单总金额为 1 元，此处请填 100）
		Map<String, String> app = new HashMap<String, String>();
		//ping++的支付对象id
		app.put("id", "app_8Wrz5CHCKCqLzTab");
		//支付app的id
		chargeParams.put("app", app);
		//如果使用的是支付宝进行付款
		if("ali".equals(orderInfo.getPayChannel())){
			//设置支付渠道
			chargeParams.put("channel", "alipay_wap");  //alipay_wap 支付宝手机网页 wx_pub_qr 微信公众号支付 wx_wap 微信wap
			Map<String, String> extra = new HashMap<String, String>();
			  //success_url 和 cancel_url 在本地测试不要写 localhost ，写 127.0.0.1，URL 后面不要加自定义参数
			  //设置支付成功的回调
			  extra.put("success_url","http://www.houheshangpin.com/member/notify");
			  //支付取消的回调地址
			  extra.put("cancel_url", "http://www.houheshangpin.com/member/notify");
			  //特定渠道发起交易时需要的额外参数
			  chargeParams.put("extra", extra);
		}	
		//微信公众号
		if("wx".equals(orderInfo.getPayChannel())){
			String url="/weChat/weChatTest";
			//将订单信息存放到session中
			request.getSession().setAttribute("orderInfo", orderInfo);
			return "{\"result\":\"success2\",\"msg\":\""+url+"\"}";
			/*chargeParams.put("channel", "wx_pub");  //alipay_wap 支付宝手机网页 wx_pub_qr 微信公众号支付 wx_wap 微信wap
				Map<String, String> extra = new HashMap<String, String>();
				  //success_url 和 cancel_url 在本地测试不要写 localhost ，写 127.0.0.1，URL 后面不要加自定义参数
				//商户操作员编号
				  extra.put("open_id", orderInfo.getOpenId());
				  chargeParams.put("extra", extra);*/
		}
		//3 位 ISO 货币代码 cny为人民币
		chargeParams.put("currency", "cny");
		//发送支付宝请求的客户端的ip地址
		chargeParams.put("client_ip", "139.224.227.142");
		//商品标题
		chargeParams.put("subject", "厚和尚品");
		//商品的描述信息
		chargeParams.put("body", "厚和尚品");
		try {
			charge = Charge.create(chargeParams);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//打印消息到日志
		logger.info(charge.toString());
//		return "{\"result\":\"success\",\"data\":\""+charge.toString()+"\"}";
		
		return charge.toString();
	}
	
	
	//显示交易成功页面
	@RequestMapping("/notify")
	public String notify(String result,String out_trade_no,HttpServletRequest request,Model model){
		String resultStr = "交易成功";
		/*//判断是否是直接购买
		int step=Integer.valueOf((String)request.getSession().getAttribute("step"));
		Map<String,OrderItemInfo> checkedMap = (Map<String,OrderItemInfo>) request.getSession().getAttribute(Constants.CHECKED_CART);			
		if(step==1){
			//取出直接购买的商品id和商品的数量
		int soldCount=(Integer) request.getSession().getAttribute("outrightPurchase");
		String productid=(String)request.getSession().getAttribute("outrightProductId" );	
		//通过产品id将销售的数量取出来然后加上去
		memberService.getProductId( productid,soldCount);
		//将session中产品id和数量给清除
		request.getSession().removeAttribute("outrightPurchase");
		request.getSession().removeAttribute("outrightProductId");
		}else if(step==2){
			//查看购物车中选中的商品
			java.util.Set<String> productids=checkedMap.keySet();
			for (String productid : productids) {
				//获取每个商品所购买的数量
			   int productSoldCount=checkedMap.get(productid).getCount();
			   //查询出商品的id
			   memberService.getProductId( productid,productSoldCount);
			}
		}
		//清空checkmap中的所有信息
		checkedMap.clear();*/
		
		model.addAttribute("result", resultStr);
		//订单编号
		model.addAttribute("orderNo", out_trade_no);
		return "/mall/paynotify";
	}
	
	@RequestMapping("/addaddress")
	public String addaddress(HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		return "/mall/addaddress";
	}
	
	//不知道该页面有和作用
	@RequestMapping("/pay.htm")
	public String paythm(HttpServletRequest request,Model model){
		return "/mall/pay";
	}
	
	//新增地址
	@RequestMapping("/saveaddr")
	public String saveaddr(MbAddrInfo mbAddrInfo,HttpServletRequest request,Model model){
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		String step = (String)request.getSession().getAttribute("step");
		if(step==null||step.equals("")){
			mbAddrInfo.setMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
			mbAddrInfo.setFullAddress(mbAddrInfo.getProvince()+" "+mbAddrInfo.getCity()+" "+mbAddrInfo.getDistrict()+" "+mbAddrInfo.getAddress());
			memberService.addMbAddr(mbAddrInfo);
			return "redirect:/member/main";
		}
		mbAddrInfo.setMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
		mbAddrInfo.setFullAddress(mbAddrInfo.getProvince()+" "+mbAddrInfo.getCity()+" "+mbAddrInfo.getDistrict()+" "+mbAddrInfo.getAddress());
		memberService.addMbAddr(mbAddrInfo);
		return "redirect:/member/prepay/"+step;
	}
	
	
	
	
	//移除会员信息跳到首页
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,Model model){
		request.getSession().removeAttribute(Constants.LOGIN_MEMBER);
		return "/index";
	}
	
	//查看订单信息。传入的参数永远都是all永远只会查询排序后的前十条数据
	@RequestMapping("/orderlist/{otype}")
	public String orderlist(@PathVariable("otype") String otype,HttpServletRequest request,Model model,Integer  page){
		//判断会员信息是否登录
		if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
			return "mall/login";
		}
		//根据会员编号
		double totalNumber=memberService.getCount((String)request.getSession().getAttribute(Constants.MEMBER_ID));	
		Map<String,Object> params = new HashMap<String,Object>();
		if(page==null||page==0){
			model.addAttribute("page",0);
			params.put("startIndex", 0);
		}else{
			model.addAttribute("page",page);
			params.put("startIndex",(page)*5);
		}
		params.put("pageSize",5);
		params.put("memberId",request.getSession().getAttribute(Constants.MEMBER_ID));
		String title = "";
		switch (otype) {
		case "all":
			params.put("orderStatus", null);
			title = "全部订单";
			break;
		case "waitpay":
			params.put("orderStatus", "0");
			title = "待支付订单";
			break;
		case "waitship":
			params.put("orderStatus", "2");
			params.put("transferStatus", "0");
			title = "待发货订单";
			break;
		case "shiped":
			params.put("orderStatus", "2");
			params.put("transferStatus", "2");
			title = "已发货订单";
			//查询总的退货条数
			double totalPage=memberService.getCountOrderList((String)request.getSession().getAttribute(Constants.MEMBER_ID));
			//只根据订单的状态和发货的状态来查询数据显示信息
			List<OrderInfo>  shipmentsList= memberService.getOrderListByParams(params);
			model.addAttribute("title", title);
			model.addAttribute("haveorder", shipmentsList.size());
			model.addAttribute("shipmentsList", shipmentsList);
			model.addAttribute("totalCount", (int)Math.ceil(totalPage/5));
			return 	"/mall/shipmentslist" ;
		case "done":
			params.put("orderStatus", "2");
			params.put("transferStatus", "2");
			title = "已完成订单";
			break;
		default:
			break;
		}
		//根据case是all则取的是倒序后的十条数据。每一个订单信息都对应订单详细信息
		List<OrderInfo> orderList = memberService.getOrderListByParams(params);
		model.addAttribute("haveorder", orderList.size());
		model.addAttribute("orderList", orderList);
		model.addAttribute("title", title);
		model.addAttribute("totalCount", (int)Math.ceil(totalNumber/5));
		return "/mall/orderlist";
	}
	
	
		//跳转支付页面
		@RequestMapping("/backPay")
		public String orderInfo(String orderId ,HttpServletRequest request , Model model){
			if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
				return "mall/login";
			}
			//根据会员的编号来获取会员的信息
			MbAddrInfo mbAddrInfo = memberService.getAddrByMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
			model.addAttribute("mbAddrInfo", mbAddrInfo);
				//通过订单编号来查询当前的订单详细列表
			     OrderInfo orderInfo=memberService.getOrderInfoById(orderId);
			     List<OrderItemInfo> itemList=memberService.getOrderItemListByOrderId(orderId);
			     model.addAttribute("itemList", itemList);
			     model.addAttribute("orderInfo", orderInfo);
				return "/mall/prepay";
		}
		
		
		
		//显示会员的地址视图
		@RequestMapping("showMemberAddress")
		public String MemberAddress(HttpServletRequest request,Model model){
			if(request.getSession().getAttribute(Constants.LOGIN_MEMBER)==null){
				return  "/mall/login";
			}
			//通过会员id来查询地址
			String memberId=(String) request.getSession().getAttribute(Constants.MEMBER_ID);
			MbAddrInfo mbAddrInfo=memberService.showAddress(memberId);
			model.addAttribute("mbAddrInfo", mbAddrInfo);
			return "/mall/memberaddresslist";
		}
		
		//修改地址编辑页面
		@RequestMapping("/updateAddress")
		public  String updateAddress(@RequestParam String pid ,Model model){
			MbAddrInfo mbAddress=memberService.showAddress(pid);
			model.addAttribute("mbAddress",mbAddress);
			return "/mall/editAddress";
		}
		
		//修改地址
		@RequestMapping("/editAddress")
		public String saveAddress(MbAddrInfo mbAddrInfo,HttpServletRequest request){
			String memberId=(String) request.getSession().getAttribute(Constants.MEMBER_ID);
			mbAddrInfo.setMemberId(memberId);
			memberService.updateAddress(mbAddrInfo);	
			return "redirect:/member/showMemberAddress";
		}
		
		
		//查询快递单号返回所使用的快递物流
		@ResponseBody
		@RequestMapping("/trackingNumberCheck")
		public String expressNumberCheck(HttpServletRequest request){
			try {
			String orderId=request.getParameter("orderId");
			OrderInfo orderInfo=memberService.selectOrderinfo(orderId);
			//获取物流编号
			String trackingNumber=orderInfo.getTransferNo().trim();
			KdApiOrderDistinguish kdApiOrderDistinguish=new KdApiOrderDistinguish();
			return  kdApiOrderDistinguish.getOrderTracesByJson(trackingNumber);
			} catch (Exception e) {
				e.printStackTrace();
				return "\"success\":\"失败\"";
			}
		}
		
		
		//显示物流信息
		@RequestMapping(value="/trackingInformationCheck")
		public String trackingInformation(String companyCode,String trackingNumber,HttpServletRequest request,Model model){
			try {
				//定义一个查询的变量
			TrackingInFormation trackingInFormation=null;
			KdniaoTrackQueryAPI api=new KdniaoTrackQueryAPI();
			if(trackingNumber==null){
				//获取请求的后面的参数
				int urlParam=request.getQueryString().lastIndexOf("=");
				trackingNumber=request.getQueryString().substring(urlParam+1).trim();
				String result=api.getOrderTracesByJson(companyCode,trackingNumber);
				//第一个参数是物流编码，第二个参数是物流编号
				System.out.println(result+".1111..........");
				// ObjectMapper类用序列化与反序列化映射器  
				trackingInFormation = JSON.parseObject(result,TrackingInFormation.class);
			}else{
				//第一个参数是物流编码，第二个参数是物流编号
				String result=api.getOrderTracesByJson(companyCode,trackingNumber);
				System.out.println(result+"...........");
				// ObjectMapper类用序列化与反序列化映射器  
				trackingInFormation = JSON.parseObject(result, TrackingInFormation.class);
			}
			//查询快递的轨迹
				model.addAttribute("trackingInFormation",trackingInFormation);
				model.addAttribute("traces", "目前系统繁忙请稍后查询");
				return "/mall/trackinginformation";
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
			
		}
		
		
		//跳转到退货页面
		@RequestMapping("orderUnsbscribe")
		public String orderUnsbscribe(String orderId ,Model model,HttpServletRequest request){
			//判断会员是否登录
			if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
				return "mall/login";
			}
			//查询订单信息表中的信息
			 OrderInfo orderInfo=memberService.getOrderInfoById(orderId);
			 //通过订单号去查询对应的订单详细列表
			 List<OrderItemInfo> orderItemInfos=memberService.getOrderItemListByOrderId(orderId);
			 model.addAttribute("orderItemInfos",orderItemInfos);
			 model.addAttribute("orderInfo",orderInfo);
			return "/mall/salesreturn";
		}
		
		
		//显示填写退货信息页面
		@RequestMapping("salasreturninformation")
		public String returnFachang(ReturnFanchang returnFanchang,Model model,HttpServletRequest request){
			//判断会员是否登录
			if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
				return "mall/login";
			}
			//获取会员的id
			model.addAttribute("returnFanchang",returnFanchang);
			model.addAttribute("memberId",request.getSession().getAttribute(Constants.MEMBER_ID));
			return "/mall/salasreturninformation";
		}
		
		//保存退货新信息
		@RequestMapping("/saveReturnInformation")
		public String saveReturnInformation(ReturnFanchang returnFanchang,HttpServletRequest request){
			//判断会员是否登录
			if(request.getSession().getAttribute(Constants.LOGIN_MEMBER) == null){
				return "mall/login";
			}
			Date date =new Date();
			returnFanchang.setSalesReturnTime(date);
			returnFanchang.setMemberId((String)request.getSession().getAttribute(Constants.MEMBER_ID));
			memberService.saveSalesReturnInformation(returnFanchang);
			//修改订单的状态和物流的状态
			memberService.updateOrderStatus(returnFanchang.getOrderId());
			return "redirect:/member/main";
		}
}
